package com.winbomb.simulife.game.screens;

import android.graphics.Color;

import com.winbomb.simulife.base.IJob;
import com.winbomb.simulife.base.IJobManager;
import com.winbomb.simulife.framework.Game;
import com.winbomb.simulife.framework.Screen;
import com.winbomb.simulife.framework.Input.TouchEvent;
import com.winbomb.simulife.game.GameScreen;
import com.winbomb.simulife.game.TouchArea;

public class FindJobScreen extends Screen {

	final TouchArea mainArea = new TouchArea(10, 30, 300, 400);
	final TouchArea finishArea = new TouchArea(10, 30, 300, 400);

	private IJob[] jobList;
	/** */
	boolean bFinished;
	/** 是否应聘成功 */
	boolean bAccepted;

	public FindJobScreen(Game game) {
		super(game);

		bFinished = false;
		bAccepted = false;
		IJobManager jobManager = game.getWorld().getJobManager();
		jobList = jobManager.getAvailableJobs();
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void present(float deltaTime) {
		g.clear(Color.WHITE);

		// draw jobs
		for (int i = 0; i < jobList.length; i++) {
			g.drawRect(10, 30 + 50 * i, 300, 49, Color.BLACK);
			g.drawText(jobList[i].getCompanyName(), 60, 38 + 50 * i);
			g.drawText(jobList[i].getJobTitle().toString(), 60, 56 + 50 * i);
			g.drawText(String.valueOf(jobList[i].getSalary()), 134, 56 + 50 * i);
		}

		if (bFinished) {
			g.drawRect(10, 190, 300, 100, Color.BLUE);
			if (bAccepted) {
				g.drawText("恭喜您应聘成功", 60, 240);
			} else {
				g.drawText("抱歉您应聘失败", 60, 240);
			}

			g.drawRect(150, 250, 20, 20, Color.BLUE);
		}
	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(float deltaTime) {
		updateTouchEvents();

		for (TouchEvent event : touchEvents) {
			if (event.type != TouchEvent.TOUCH_UP) {
				continue;
			}

			if (!bFinished && mainArea.isBound(event)) {
				int idx = getSelectedIndex(event.x, event.y);
				if (idx < 0 || idx >= jobList.length || jobList[idx] == null) {
					return;
				}

				bFinished = true;

				// 判断是否能够得到这份工作
				if (jobList[idx].apply()) {
					game.getWorld().getMaster().setJob(jobList[idx]);
					bAccepted = true;
				}

			} else if (bFinished && finishArea.isBound(event)) {
				// 返回
				game.getWorld().nextEvent();
				game.setScreen(new GameScreen(game));
			}
		}

	}

	private int getSelectedIndex(int x, int y) {
		return (y - 30) / 50;
	}

}
